import wepy from 'wepy'
import Promise from 'promise-polyfill'
import 'wepy-async-function'
let root_url = 'https://pintuan.weixin.zhiyuanch.com/api'
async function request(data, success, access_token, error401)
{
  wepy.showLoading({title:'加载中..'})
  let header = {}
  if(access_token) {
    header.Authorization = 'Bearer ' + access_token
  }
  if(!data.method) {
    data.method = 'GET'
  }
  header.Accept = 'application/vnd.52jjss.v1+json'
  data.url = root_url + data.url
  data.header = header
  wepy.request(data).then((res) => {
    wepy.hideLoading()
    if (res.statusCode === 200) {
      success(res.data)
    }else {
      if(res.statusCode === 401) {
        wepy.showToast({
          title: '登录校检失败，请重新登录.',
          icon: 'none',
          duration: 2000
        })
        try {
          wepy.removeStorageSync('session')

        } catch (e) {
          // Do something when catch error
        }
        if(error401) {
          error401()
        }
      }else if(res.statusCode === 500) {
        console.log(res)
        wepy.showToast({
          title: '网络出错，请稍后再试.',
          icon: 'none',
          duration: 2000
        })
      }else{
        wepy.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        })
      }
    }

  }).catch((res)=>{
    wepy.hideLoading()
  })
}
async function loginUsers (res, that) {
  console.log(that)
  //let login = await wepy.login()
  wx.login({
      success: function(login) {
        if (login.code) {
          //发起网络请求
          request({
            url: '/auth/login',
            data: {
              code: login.code,
              encryptedData: res.encryptedData,
              iv: res.iv
            },
            method: 'POST'
          }, function(res) {
            if (res.status_code == 200) {
              wepy.showToast({
                title: '登录成功.',
                icon: 'none',
                duration: 2000
              })
              try {
                that.session = res.item
                that.setData({session: res.item, userInf: res.item.user_info})
                that.$apply()
                wepy.setStorageSync('session', res.item)

                if(that.info) {
                  let data = {
                    is_default: 1
                  }
                  that.getAddressItem(data, res.item)
                }

              } catch (e) {
                console.log(e)
              }
            } else {
              console.log(res)
            }
          }, null, function(){
            //loginUsers (res, that)
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
  })

}
function logginUsersT(res, that) {
  wepy.login().then((login)=>{
    console.log(login)
    request({
      url: '/auth/login',
      data: {
        code: login.code,
        encryptedData: res.encryptedData,
        iv: res.iv
      },
      method: 'POST'
    }, function(res) {
      if (res.status_code == 200) {
        try {
          that.session = res.item
          that.setData({session: res.item, userInf: res.item.user_info})
          that.$apply()
          wepy.setStorageSync('session', res.item)

        } catch (e) {
          console.log(e)
        }
      } else {
        console.log(res)
      }
    })
  })
}

function countdown(that) {

  var NowTime = new Date().getTime();
  let total_micro_second = 0;
  let EndTime = 0;
  if (that.data.goodsInf){
    let info = that.data.goodsInf;
    EndTime = (info['starttimes']);
    total_micro_second = EndTime - NowTime;
    if (info['starttimes'] > NowTime ) {
      info['clock'] = '距离开始：'+dateformat(total_micro_second);
    } else if (info['endtimes'] < NowTime) {
      info['clock'] = "已经截止";
    }else {
      info['clock'] = '距离结束：' + dateformat(info['endtimes'] - NowTime);
    }

    that.setData({
      goodsInf: info
    });
  } else if (that.data.history_goods_list){
    let list = that.data.history_goods_list
    for (let i in list) {
      EndTime = (list[i]['starttimes']);

      total_micro_second = EndTime - NowTime;

      if (list[i]['starttimes'] > NowTime) {
        list[i]['clock'] = '距离开始：' + dateformat(total_micro_second);
      } else if (list[i]['endtimes'] < NowTime) {
        list[i]['clock'] = "已经截止";
      } else {
        list[i]['clock'] = '距离结束：' + dateformat(list[i]['endtimes'] - NowTime);
      }

      if (total_micro_second <= 0) {
        list[i]['clock'] = "已经截止";
      } else {
        list[i]['clock'] = dateformat(total_micro_second);
      }

    }
    that.setData({
      history_goods_list: list
    });
  }


  setTimeout(function () {
    total_micro_second -= 1000;
    countdown(that);
  }
    , 1000)
}
// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
}
module.exports = {
  request,
  countdown,
  loginUsers,
  logginUsersT
}
